/**
 * allows for downloading of grid data (store) directly into excel Method:
 * extracts data of gridPanel store, uses columnModel to construct XML excel
 * document, converts to Base64, then loads everything into a data URL link.
 *
 * @author Animal <extjs support team>
 *
 */

var versionFinish = false;
function commafy(num) {
    if (isNaN(num)) {
        return "";
    }
    num = num + "";
    var xiaoshu = "";
    if (num.indexOf(".") != -1) {
        xiaoshu = num.substring(num.indexOf("."), num.length);
        num = num.substring(0, num.indexOf("."));
    }
    if (/^.*\..*$/.test(num)) {
        varpointIndex = num.lastIndexOf(".");
        varintPart = num.substring(0, pointIndex);
        varpointPart = num.substring(pointIndex + 1, num.length);
        intPart = intPart + "";
        var re = /(-?\d+)(\d{3})/
        while (re.test(intPart)) {
            intPart = intPart.replace(re, "$1,$2")
        }
        num = intPart + "." + pointPart;
    } else {
        num = num + "";
        var re = /(-?\d+)(\d{3})/
        while (re.test(num)) {
            num = num.replace(re, "$1,$2")
        }
    }
    return num + xiaoshu;
}
var Base64 = (function () {

    // private property
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // private method for UTF-8 encoding
    function utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    }

    // public method for encoding
    return {
        encode: (typeof btoa == 'function') ? function (input) {
            return btoa(input);
        } : function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = utf8Encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
                    + keyStr.charAt(enc3) + keyStr.charAt(enc4);
            }
            return output;
        }
    };
})();

$
    .extend(
    $.fn.datagrid.methods,
    {
        getExcelXml: function (jq, param) {
            var worksheet = this.createWorksheet(jq, param);
            // alert($(jq).datagrid('getColumnFields'));
            var totalWidth = 0;
            var cfs = $(jq).datagrid('getColumnFields');
            for (var i = 1; i < cfs.length; i++) {
                totalWidth += $(jq).datagrid('getColumnOption',
                    cfs[i]).width;
            }
            // var totalWidth =
            // this.getColumnModel().getTotalWidth(includeHidden);
            return '<xml version="1.0" encoding="utf-8">'
                + '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:o="urn:schemas-microsoft-com:office:office">'
                + '<o:DocumentProperties><o:Title>'
                + param.title
                + '</o:Title></o:DocumentProperties>'
                + '<ss:ExcelWorkbook>'
                + '<ss:WindowHeight>'
                + worksheet.height
                + '</ss:WindowHeight>'
                + '<ss:WindowWidth>'
                + worksheet.width
                + '</ss:WindowWidth>'
                + '<ss:ProtectStructure>False</ss:ProtectStructure>'
                + '<ss:ProtectWindows>False</ss:ProtectWindows>'
                + '</ss:ExcelWorkbook>'
                + '<ss:Styles>'
                + '<ss:Style ss:ID="Default">'
                + '<ss:Alignment ss:Vertical="Top" ss:Horizontal="Right"  />'
                + '<ss:Font ss:FontName="arial" ss:Size="10" />'
                + '<ss:Borders>'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Top" />'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Bottom" />'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Left" />'
                + '<ss:Border ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Right" />'
                + '</ss:Borders>'
                + '<ss:Interior />'
                + '<ss:NumberFormat />'
                + '<ss:Protection />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="Default1">'
                + '<ss:Alignment ss:Vertical="Top" ss:Horizontal="Center"  />'
                + '<ss:Font ss:FontName="arial" ss:Size="10" />'
                + '<ss:Borders>'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Top" />'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Bottom" />'
                + '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Left" />'
                + '<ss:Border ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Right" />'
                + '</ss:Borders>'
                + '<ss:Interior />'
                + '<ss:NumberFormat />'
                + '<ss:Protection />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="title">'
                + '<ss:Borders />'
                + '<ss:Font />'
                + '<ss:Alignment  ss:Vertical="Center" ss:Horizontal="Center" />'
                + '<ss:NumberFormat ss:Format="@" />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="headercell">'
                + '<ss:Font ss:Bold="1" ss:Size="10" />'
                + '<ss:Alignment  ss:Horizontal="Center" />'
                + '<ss:Interior ss:Pattern="Solid"  />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="headercell2">'
                + '<ss:Font ss:Bold="1" ss:Size="10" />'
                + '<ss:Alignment  ss:Horizontal="Right" />'
                + '<ss:Interior ss:Pattern="Solid"  />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="even">'
                + '<ss:Interior ss:Pattern="Solid"  />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="even" ss:ID="evendate">'
                + '<ss:NumberFormat ss:Format="yyyy-mm-dd" />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="even" ss:ID="evenint">'
                + '<ss:NumberFormat ss:Format="0" />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="even" ss:ID="evenfloat">'
                + '<ss:NumberFormat ss:Format="0.00" />'
                + '</ss:Style>'
                + '<ss:Style ss:ID="odd">'
                + '<ss:Interior ss:Pattern="Solid"  />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="odd" ss:ID="odddate">'
                + '<ss:NumberFormat ss:Format="yyyy-mm-dd" />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="odd" ss:ID="oddint">'
                + '<ss:NumberFormat ss:Format="0" />'
                + '</ss:Style>'
                + '<ss:Style ss:Parent="odd" ss:ID="oddfloat">'
                + '<ss:NumberFormat ss:Format="0.00" />'
                + '</ss:Style>'
                + '</ss:Styles>'
                + worksheet.xml + '</ss:Workbook>';
        },

        createWorksheet: function (jq, param) {
            // Calculate cell data types and extra class names which
            // affect formatting
            var cellType = [];
            var cellTypeClass = [];
            // var cm = this.getColumnModel();
            var totalWidthInPixels = 0;
            var colXml = '';
            var headerXml = '';
            var visibleColumnCountReduction = 0;
            var cfs = $(jq).datagrid('getColumnFields');
            var colCount = cfs.length;
            for (var i = 0; i < colCount; i++) {
                if (cfs[i] != '') {
                    var w = $(jq).datagrid('getColumnOption',
                        cfs[i]).width;
                    totalWidthInPixels += w;
                    if (cfs[i] === "") {
                        cellType.push("None");
                        cellTypeClass.push("");
                        ++visibleColumnCountReduction;
                    } else {

                        colXml += '<ss:Column ss:AutoFitWidth="1" ss:Width="130" />';

                        if (i == 0)
                            headerXml += '<ss:Cell ss:StyleID="headercell">';
                        else
                            headerXml += '<ss:Cell ss:StyleID="headercell2">';

                        headerXml += '<ss:Data ss:Type="String">'
                            + $(jq).datagrid('getColumnOption',
                            cfs[i]).title
                            + '</ss:Data>'
                            + '<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>';
                        cellType.push("String");
                        cellTypeClass.push("");
                    }
                }
            }
            var visibleColumnCount = cellType.length
                - visibleColumnCountReduction;

            var result = {
                height: 9000,
                width: Math.floor(totalWidthInPixels * 30) + 50
            };

            var rows = $(jq).datagrid('getRows');
            // Generate worksheet header details.
            var t = '<ss:Worksheet ss:Name="'
                + param.title
                + '">'
                + '<ss:Names>'
                + '<ss:NamedRange ss:Name="Print_Titles" ss:RefersTo="=\''
                + param.title + '\'!R1:R2" />' + '</ss:Names>'
                + '<ss:Table x:FullRows="1" x:FullColumns="1"'
                + ' ss:ExpandedColumnCount="'
                + (visibleColumnCount + 2)
                + '" ss:ExpandedRowCount="' + (rows.length + 2)
                + '">' + colXml
                + '<ss:Row ss:AutoFitHeight="1">' + headerXml
                + '</ss:Row>';

            // Generate the data rows from the data in the Store
            // for (var i = 0, it = this.store.data.items, l =
            // it.length; i < l; i++) {
            for (var i = 0, it = rows, l = it.length; i < l; i++) {
                t += '<ss:Row>';
                var cellClass = (i & 1) ? 'odd' : 'even';
                r = it[i];
                var k = 0;
                for (var j = 0; j < colCount; j++) {
                    // if ((cm.getDataIndex(j) != '')
                    if (cfs[j] != '') {
                        // var v = r[cm.getDataIndex(j)];
                        var v = r[cfs[j]];
                        if (cellType[k] !== "None") {
                            if (j == 0)
                                t += '<ss:Cell ss:StyleID="Default1"><ss:Data ss:Type="'
                                    + cellType[k] + '">';
                            else
                                t += '<ss:Cell ss:StyleID="Default"><ss:Data ss:Type="'
                                    + cellType[k] + '">';
                            if (cellType[k] == 'DateTime') {
                                t += v.format('Y-m-d');
                            } else {
                                if (j == 0)
                                    t += v;
                                else
                                    t += v;
                            }
                            t += '</ss:Data></ss:Cell>';
                        }
                        k++;
                    }
                }
                t += '</ss:Row>';
            }

            result.xml = t
                + '</ss:Table>'
                + '<x:WorksheetOptions>'
                + '<x:PageSetup>'
                + '<x:Layout x:CenterHorizontal="1" x:Orientation="Landscape" />'
                + '<x:Footer x:Data="Page &amp;P of &amp;N" x:Margin="0.5" />'
                + '<x:PageMargins x:Top="0.5" x:Right="0.5" x:Left="0.5" x:Bottom="0.8" />'
                + '</x:PageSetup>'
                + '<x:FitToPage />'
                + '<x:Print>'
                + '<x:PrintErrors>Blank</x:PrintErrors>'
                + '<x:FitWidth>1</x:FitWidth>'
                + '<x:FitHeight>32767</x:FitHeight>'
                + '<x:ValidPrinterInfo />'
                + '<x:VerticalResolution>600</x:VerticalResolution>'
                + '</x:Print>'
                + '<x:Selected />'
                + '<x:DoNotDisplayGridlines />'
                + '<x:ProtectObjects>False</x:ProtectObjects>'
                + '<x:ProtectScenarios>False</x:ProtectScenarios>'
                + '</x:WorksheetOptions>' + '</ss:Worksheet>';
            // alert(result.xml);
            return result;
        }
    });

function indexOf(array, value) {
    var length = array.length;
    for (var i = 0; i < length; i++) {
        if (array[i] == value)
            return i;
    }
    return -1;
}

function remove(array, dx) {
    if (isNaN(dx) || dx > array.length) {
        return false;
    }
    for (var i = 0, n = 0; i < array.length; i++) {
        if (array[i] != array[dx]) {
            array[n++] = array[i]
        }

    }
    array.length -= 1
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}
function drawUserCharts(data, divId, type, hasRunWake) {

    var categories = [];
    var series = [
        {
            name: "新增用户",
            data: []
        },

        {
            name: "启动次数",
            data: []
        },
        {
            name: "唤醒用户",
            data: []
        },
        {
            name: "唤醒次数",
            data: []
        },
        {
            name: "联网用户",
            data: []
        },
        {
            name: "使用次数",
            data: []
        }
    ];
    if (hasRunWake) {
        series.push({
            name: "使用用户",
            data: []
        });
    }
    for (var i = 0; i < data.length; i++) {
        var cate = data[i].groupField;
        if (type == "time")
            cate = cate.substring(4, 8);
        else if (type == "area") {
            if (cate != "-1")
                cate = city[parseInt(cate)];
            else
                cate = city[cate];
        } else if (type == "platform") {

            for (var j = 0; j < platform.length; j++) {
                if (platform[j].platformId == cate) {
                    cate = platform[j].name;
                    break;
                }
            }
        }
        categories.push(cate);
        series[0].data.push(data[i]["newUserNum"]);
        series[1].data.push(data[i]["runNum"]);
        series[2].data.push(data[i]["wakeUserNum"]);
        series[3].data.push(data[i]["wakeNum"]);
        series[4].data.push(data[i]["useUserNum"]);
        series[5].data.push(data[i]["useNum"]);
        if (hasRunWake) {
            series[6].data.push(data[i]["useUserNumRunandawake"]);
        }
    }
    $('#' + divId).highcharts(
        {
            chart: {
                type: 'line'
                // marginRight: 130,
                // marginBottom: 25
            },

            credits: {
                enabled: false
            },
            title: {
                // text: '移动用户趋势图'
                text: ''
            },
            xAxis: {
                categories: categories
            },
            yAxis: {

                min: 0,
                title: {
                    text: ''
                },
                labels: {
                    formatter: function () {// 设置纵坐标值的样式
                        return commafy(this.value);
                    }
                },
                plotLines: [
                    {
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }
                ]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' + this.x
                        + ': ' + commafy(this.point.y + "");
                }
            },
            legend: {
                layout: 'horizontal',
                align: 'center',
                verticalAlign: 'top',

                borderWidth: 0
            },
            series: series
        });

}
function switchChart(id) {
    $(".pie").hide();

    $("#pie" + id).show();
    /*
     * for(var i=0;i<7;i++) {if(i==index)
     * document.getElementById("pie"+index).style.display="block"; else
     * document.getElementById("pie"+index).style.display="none"; }
     */

}
function drawUserChartsPie(data, divId, type, hasRunWake) {

    var html = "<table><tr><td style='width:15%'></td><td style='width:50%'>";
    var columnLength = 6;
    if (hasRunWake) {
        columnLength = 7;
    }
    for (var i = 0; i < columnLength; i++) {
        html += "<div style='display:none' id='pie" + i + "' class='pie'> " + i
            + "</div>";
    }
    html += "</td><td><ul>";
    html += '<li><a href="#" id="piebutton0" onclick="switchChart(0);" class="easyui-linkbutton">新增用户</a></li><br> ';
    html += '<li><a href="#" id="piebutton2" onclick="switchChart(1);" class="easyui-linkbutton">启动次数</a></li><br> ';
    html += '<li><a href="#" id="piebutton3" onclick="switchChart(2);" class="easyui-linkbutton"> 唤醒用户</a></li><br> ';
    html += '<li><a href="#" id="piebutton4" onclick="switchChart(3);" class="easyui-linkbutton"> 唤醒次数</a></li><br> ';
    html += '<li><a href="#" id="piebutton5" onclick="switchChart(4);" class="easyui-linkbutton"> 联网用户</a></li><br> ';
    html += '<li><a href="#" id="piebutton6" onclick="switchChart(5);" class="easyui-linkbutton"> 使用次数</a></li><br> ';
    if (hasRunWake) {
        html += '<li><a href="#" id="piebutton7" onclick="switchChart(6);" class="easyui-linkbutton"> 使用用户</a></li></ul></td></tr><table> ';
    }

    $("#" + divId).html(html);

    $.parser.parse("#" + divId);

    var ss = [
        {
            name: "新增用户",
            field: "newUserNum"
        },
        {
            name: "启动次数",
            field: "runNum"
        },
        {
            name: "唤醒用户",
            field: "wakeUserNum"
        },
        {
            name: "唤醒次数",
            field: "wakeNum"
        },
        {
            name: "联网用户",
            field: "useUserNum"
        },
        {
            name: "使用次数",
            field: "useNum"
        }
    ];

    if (hasRunWake) {
        ss.push({
            name: "使用用户",
            field: "useUserNumRunandawake"
        });
    }
    for (var k = 0; k < columnLength; k++) {
        var series = [
            {
                "type": 'pie',
                "name": type,
                "data": []
            }
        ];
        for (var i = 0; i < data.length; i++) {
            var cate = data[i].groupField;
            if (type == "time")
                cate = cate.substring(4, 8);
            else if (type == "area") {
                if (cate != "-1")
                    cate = city[parseInt(cate)];
                else
                    cate = city[cate];
            } else if (type == "platform") {

                for (var j = 0; j < platform.length; j++) {
                    if (platform[j].platformId == cate) {
                        cate = platform[j].name;
                        break;
                    }
                }
            }

            series[0]["data"].push([ cate, data[i][ss[k].field] ]);
            series[0]["data"].sort(function (a, b) {
                return a[1] > b[1] ? -1 : 1
            });
        }
        $('#pie' + k).highcharts(
            {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                credits: {
                    text: ''
                },
                title: {
                    text: ss[k].name
                },
                tooltip: {
                    // pointFormat: ' <b>commafy({point.y})</b>'
                    formatter: function () {

                        return this.point.name + '<b>'
                            + commafy(this.point.y + "") + "</b>";
                        ;
                    }
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            percentageDecimals: 2,
                            enabled: true,
                            color: '#000000',
                            connectorColor: '#000000',
                            formatter: function () {
                                percentage = this.point.percentage + "";
                                if (percentage.indexOf(".") != -1)
                                    percentage = percentage.substring(0,
                                        percentage.indexOf(".") + 3);
                                return '<b>' + this.point.name + '</b>: '
                                    + percentage + "%";
                                ;
                            }
                        }
                    }
                },
                series: series

            });
    }
    switchChart(0);
}

function drawPlayChartsPie(data, divId, type) {

    var html = "<table><tr><td width='70px'></td><td>"
    for (var i = 0; i < 7; i++) {
        html += "<div style='display:none' id='pie" + i + "' class='pie'> " + i
            + "</div>";
    }
    html += "</td><td><ul>";
    html += '<li><a href="#" id="piebutton0" onclick="switchChart(0);" class="easyui-linkbutton">VV</a></li><br> ';
    html += '<li><a href="#" id="piebutton1" onclick="switchChart(1);" class="easyui-linkbutton">RealVV</a></li><br> ';
    html += '<li><a href="#" id="piebutton2" onclick="switchChart(2);" class="easyui-linkbutton">FUV</a></li><br> ';
    html += '<li><a href="#" id="piebutton3" onclick="switchChart(3);" class="easyui-linkbutton">RealFUV</a></li><br> ';
    html += '<li><a href="#" id="piebutton4" onclick="switchChart(4);" class="easyui-linkbutton">播放时长（小时）</a></li><br> ';
    $("#" + divId).html(html);

    $.parser.parse("#" + divId);

    var ss = [
        {
            name: "VV",
            field: "vv"
        },
        {
            name: "realVV",
            field: "realVv"
        },
        {
            name: "FUV",
            field: "fuv"
        },
        {
            name: "realFUV",
            field: "realFuv"
        },
        {
            name: "播放时长",
            field: "playTime"
        }
    ];

    for (var k = 0; k < 5; k++) {
        var series = [
            {
                "type": 'pie',
                "name": type,
                "data": []
            }
        ];
        for (var i = 0; i < data.length; i++) {
            var cate = data[i].groupField;
            if (type == "time")
                cate = cate.substring(4, 8);
            else if (type == "area") {
                if (cate != "-1")
                    cate = city[parseInt(cate)];
                else
                    cate = city[cate];
            } else if (type == "platform") {
                for (var j = 0; j < platform.length; j++) {
                    if (platform[j].platformId == cate) {
                        cate = platform[j].name;
                        break;
                    }
                }
            } else if (type == "isonline") {
                cate = isonlines[cate];
            } else if (type == "catecode") {
                cate = categories[cate];
            }

            series[0]["data"].push([ cate, data[i][ss[k].field] ]);
            series[0]["data"].sort(function (a, b) {
                return a[1] > b[1] ? -1 : 1
            });
        }
        $('#pie' + k).highcharts(
            {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                credits: {
                    text: ''
                },
                title: {
                    text: ss[k].name
                },
                tooltip: {
                    // pointFormat: '{point.percentage:.2f}%</b>'
                    formatter: function () {
                        return this.point.name + ' <b>'
                            + commafy(this.point.y + "") + "</b>";
                    }
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {

                            enabled: true,
                            color: '#000000',
                            connectorColor: '#000000',
                            formatter: function () {
                                percentage = this.point.percentage + "";
                                if (percentage.indexOf(".") != -1)
                                    percentage = percentage.substring(0,
                                        percentage.indexOf(".") + 3);
                                return '<b>' + this.point.name + '</b>: '
                                    + percentage + "%";
                            }
                        }
                    }
                },
                series: series

            });
    }
    switchChart(0);
}
function getArray() {
    var ss = [];
    if (typeof (getFilterSet) != 'undefined') {
        var filterSet = getFilterSet(window.parent.userDefinedColumnFilterMap[url]);
        var cloneSs = new Array();
        for (var i = 0; i < kvMap.length; i++) {
            var clone = kvMap[i];
            if (!filterSet[clone.field]) {
                cloneSs.push(clone);
            }
        }
        ss = cloneSs;
    } else {
        ss = kvMap;
    }
    return ss;
}

var chartData;
function drawChartsPie(data, divId, type) {
    chartData = data;
    var html = "<table><tr><td width='70px'></td><td>"
    html += "<div  id='pie' class='pie'></div>";
    html += '</td><td valign="top"><ul>';
    var ss = getArray();
    var index = 0;
    for (var i = 0; i < ss.length; i++) {
        var kv = ss[i];
        if ((i + 1) % 9 == 0) {
            html += '</ul></td><td valign="top"><ul>';
        }
        if (kv.name == 'VV') {
            index = i;
        }
        html += '<li><a href="#" onclick="switchPieChart(' + i + ',\'' + type + '\');" class="easyui-linkbutton">' + kv.name + '</a></li><br>'
    }
    html += '</ul></td></tr><table> ';
    $("#" + divId).html(html);

    $.parser.parse("#" + divId);

    switchPieChart(index, type);
}

var kvMap = [
    {
        name: "新增用户",
        field: "newUserNum"
    },
    {
        name: "联网用户",
        field: "useUserNumRunandawake"
    },
    {
        name: "启动用户",
        field: "runUserNum"
    },
    {
        name: "启动次数",
        field: "runNum"
    },
    {
        name: "唤醒用户",
        field: "wakeUserNum"
    },
    {
        name: "唤醒次数",
        field: "wakeNum"
    },
    {
        name: "使用用户",
        field: "useUserNum"
    },
    {
        name: "使用次数",
        field: "useNum"
    },
    {
        name: "VV",
        field: "vv"
    },
    {
        name: "RealVV",
        field: "realVv"
    },
    {
        name: "FUV",
        field: "fuv"
    },
    {
        name: "RealFUV",
        field: "realFuv"
    },
    {
        name: "播放时长",
        field: "playTime"
    }
];

function switchPieChart(index, type) {
    var ss = [];
    if (typeof (getFilterSet) != 'undefined') {
        var filterSet = getFilterSet(window.parent.userDefinedColumnFilterMap[url]);
        var cloneSs = new Array();
        var count = 0;
        for (var i = 0; i < kvMap.length; i++) {
            var clone = kvMap[i];
            if (!filterSet[clone.field]) {
                cloneSs.push(clone);
            }
        }
        ss = cloneSs;
        if (ss.length == 0) {
            return;
        }
    } else {
        ss = kvMap;
    }
    var series = [
        {
            "type": 'pie',
            "name": type,
            "data": []
        }
    ];
    for (var i = 0; i < chartData.length; i++) {
        var cate = chartData[i].groupField;
        if (type == "time")
            cate = cate.substring(4, 8);
        else if (type == "area") {
            if (cate != "-1")
                cate = city[parseInt(cate)];
            else
                cate = city[cate];
        } else if (type == "platform") {
            for (var j = 0; j < platform.length; j++) {
                if (platform[j].platformId == cate) {
                    cate = platform[j].name;
                    break;
                }
            }
        } else if (type == "isonline") {
            cate = isonlines[cate];
        } else if (type == "catecode") {
            cate = categories[cate];
        } else if (type == 'mosv') {
            cate = chartData[i].mosv;
        }

        series[0]["data"].push([ cate, chartData[i][ss[index].field] ]);
        series[0]["data"].sort(function (a, b) {
            return a[1] > b[1] ? -1 : 1
        });
    }
    $('#pie').highcharts(
        {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            credits: {
                text: ''
            },
            title: {
                text: ss[index].name
            },
            tooltip: {
                // pointFormat: '{point.percentage:.2f}%</b>'
                formatter: function () {
                    return this.point.name + ' <b>'
                        + commafy(this.point.y + "") + "</b>";
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {

                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function () {
                            percentage = this.point.percentage + "";
                            if (percentage.indexOf(".") != -1)
                                percentage = percentage.substring(0,
                                    percentage.indexOf(".") + 3);
                            return '<b>' + this.point.name + '</b>: '
                                + percentage + "%";
                        }
                    }
                }
            },
            series: series

        });
}

function defaultCitys() {
    var textArray = [];
    var valueArray = [];
    for (var c in city) {
        if (c.length == 2 && c != -1) {
            textArray.push(city[c]);
            valueArray.push(c);
        }
    }

    // $("#citys").val(valueArray.join(","));
    document.getElementById("city").value = valueArray;
    document.getElementById("all").value = 0;
    setTimeout(function () {

        $('#cc').combo("setText", textArray.join(","));
    }, 1000);

}
function defaultCitys2() {

    document.getElementById("all").value = 1;

}
function handleLocationValues2() {
    var cityIds = [];
    var cityValues = $("#cc").combotree("getValues");
    for (var i = 0; i < cityValues.length; i++) {
        cityIds.push(cityValues[i]);
    }
    if (cityIds.length == 0) {
        defaultCitys();
    }

}
function handleLocationValues(area) {
    var cityValues = $("#cc").combotree("getValues");
    // 添加全国标记
    if (indexOf(cityValues, -1) != -1 && (!area)) {
        $("#all").val(1);
        return;
    } else
        $("#all").val(0);
    var cityIDs = [];
    var provinceIDs = [];
    // 移除勾选省后省下的id
    var removeCityID = [];
    for (var i = 0; i < cityValues.length; i++) {
        if (cityValues[i].length == 2) {
            provinceIDs.push(cityValues[i]);
            for (var j = 0; j < cityValues.length; j++) {
                if (cityValues[j].length == 4
                    && cityValues[j].startWith(cityValues[i]))

                    removeCityID.push(cityValues[j]);
            }
        } else
            cityIDs.push(cityValues[i]);
    }
    for (var m = 0; m < cityIDs.length; m++) {
        for (var k = 0; k < removeCityID.length; k++) {
            if (cityIDs[m] == removeCityID[k])
                remove(cityIDs, m);
        }
    }
    var cityAndProvince = [];
    for (var i = 0; i < cityIDs.length; i++)
        cityAndProvince.push(cityIDs[i]);
    for (var j = 0; j < provinceIDs.length; j++)
        cityAndProvince.push(provinceIDs[j]);
    $('#city').val(cityAndProvince);
    $('#province').val(provinceIDs);
}
function handlerDate() {
    $.fn.datebox.defaults.formatter = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + "-" + m + "-" + d;
    }
}
function setDefaultTime(days) {
    var date = new Date();
    date.setDate(date.getDate() - 1);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;
    $('#edate').datebox('setValue', y + "-" + m + "-" + d);
    date.setDate(date.getDate() - days);
    y = date.getFullYear();
    m = date.getMonth() + 1;
    d = date.getDate();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;
    $('#bdate').datebox('setValue', y + "-" + m + "-" + d);
}

function setDefaultDate() {
    var date = new Date();
    date.setDate(date.getDate() - 1);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;
    $('#idate').datebox('setValue', y + "-" + m + "-" + d);
}

function setDefaultTimeNew(days) {
    var date = new Date();
    date.setDate(date.getDate() - 1);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;
    $('#edate').datebox('setValue', y + "-" + m + "-" + d);
    if (days > 0) {
        date.setDate(date.getDate() - days);
    } else {
        date.setMonth(date.getMonth() - 1);
    }
    y = date.getFullYear();
    m = date.getMonth() + 1;
    d = date.getDate();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;
    $('#bdate').datebox('setValue', y + "-" + m + "-" + d);
}

function setDefaultTimeAndLocation(days) {

    setDefaultTime(days);

    // $('#cc').combo("setText", "全国");
    document.getElementById("all").value = "1";
    // $("#ff").appendChild("<input type='hidden' name=''")
}

function handleRealDateValues() {
    $("#bdateReal").val(reFormatDate($("#bdate").datebox("getValue")));
    $("#edateReal").val(reFormatDate($("#edate").datebox("getValue")));
}

function handleRealDateValuesNew(value) {
    if (value == 1) {
        $("#bdateReal").val(getIntDate($("#bdate").datebox("getValue")));
        $("#edateReal").val(getIntDate($("#edate").datebox("getValue")));
        $("#idate").val(reFormatDate($("#edate").datebox("getValue")));
    } else {
        $("#bdateReal").val(getIntDate($("#startDate").combobox("getValue")));
        $("#edateReal").val(getIntDate($("#endDate").combobox("getValue")));
    }
}

function handleRealDateValuesNew2(value) {
    if (value == 1) {
        $("#bdateReal").val(getIntDate($("#bdate").datebox("getValue")));
        $("#edateReal").val(getIntDate($("#edate").datebox("getValue")));
        $("#idate").val(reFormatDate($("#edate").datebox("getValue")));
    } else {
        $("#bdateReal").val(getIntDate($("#startDate").combobox("getValue")));
        $("#edateReal").val(getIntDate($("#endDate").combobox("getValue")));
        $("#idate").val(getIntDate($("#endDate").datebox("getValue")));

    }
}

function reFormatDate(date) {
    var year = date.split("-")[0];
    var month = date.split("-")[1].length == 1 ? ("0" + date.split("-")[1])
        : date.split("-")[1];
    var day = date.split("-")[2].length == 1 ? ("0" + date.split("-")[2])
        : date.split("-")[2];
    return year + "" + month + "" + day;
}
function checkAll(check) {
    var versionsBox = document.getElementsByName("versions");
    for (var i = 0; i < versionsBox.length; i++)
        versionsBox[i].checked = check;
}
function registerPlatformSelect() {
    $('#platform')
        .combobox(
        {
            onSelect: function (param) {
                $
                    .get(
                    contextPath
                        + "/userDataStat/platformVersions",
                    {
                        "platform": param.value
                    },
                    function (data, status) {
                        var data = eval('(' + data
                            + ')');
                        if (data.length != 0) {
                            data = data.reverse();
                            var versions = '<tr><td><input type="checkbox" checked="true" onclick="checkAll(this.checked)">全部</td>';

                            for (var i = 0; i < data.length; i++) {
                                if (data[i].status == 1) {
                                    var version = '<td><input type="checkbox" value="'
                                        + data[i].versionName
                                        + '" name="versions" checked="true">'
                                        + data[i].versionName
                                        + "</td>";
                                    versions += version;
                                    var j = i + 2;
                                    if (j > 0
                                        && j % 15 == 0
                                        && j != (data.length - 1))
                                        versions += "</tr>";
                                }

                            }
                            versions += "</tr>";
                            $("#versions").html(
                                versions);
                            versionFinish = true;
                        } else {
                            $("#versions").html("");
                        }
                    }

                );
            }
        });

}
function handlerCheck() {
    $('#cc').combotree(
        {
            onCheck: function (node, checked) {
                var checkedNode = $('#cc').combotree("tree").tree(
                    "getChecked");
                var realNode = [];
                var excludeProvince = [];
                var excludeCitys = [];
                var ss = [];
                for (var i = 0; i < checkedNode.length; i++) {
                    if (checkedNode[i].id == "-1") {
                        ss = [ "全国" ];
                        break;
                    } else if (checkedNode[i].id.length == 2) {
                        realNode.push(checkedNode[i]);
                        excludeProvince.push(checkedNode[i].id);
                    } else {
                        realNode.push(checkedNode[i]);
                    }
                }
                for (var k = 0; k < realNode.length; k++) {
                    for (var m = 0; m < excludeProvince.length; m++) {
                        if (realNode[k].id.length == 4
                            && realNode[k].id
                            .startWith(excludeProvince[m]))
                            excludeCitys.push(realNode[k].id);
                    }
                }
                for (var n = 0; n < realNode.length; n++) {
                    if (indexOf(excludeCitys, realNode[n].id) == -1)
                        ss.push(realNode[n].text);
                }
                $('#cc').combo("setText", ss.join(","));
            }
        });
}

function isWeekend(date) {
    var ds = date + "";
    if (ds.length != 8) {
        return false;
    }
    var year = ds.substring(0, 4);
    var month = ds.substring(4, 6);
    var day = ds.substring(6, 8);
    var d = new Date(year + "/" + month + "/" + day);
    var monthOfDay = d.getDay();
    return monthOfDay == 6 || monthOfDay == 0;
}

var tooltips = {
    newUserNum: '第一次使用客户端的独立用户数',
    useUserNum: '安装了客户端并与服务器有连接的独立用户数',
    runUserNum: '启动客户端的独立用户数',
    runNum: '启动客户端的次数',
    wakeUserNum: '将客户端从后台唤醒的独立用户数',
    wakeNum: '将客户端从后台唤醒的次数',
    useUserNumRunandawake: '使用客户端的独立用户数，取启动和唤醒用户的滤重值',
    useNum: '使用客户端的次数，等于启动和唤醒之和',
    vv: '开始播放视频的次数',
    realVv: '成功播放第一帧的次数',
    fuv: '开始播放视频的独立用户数',
    realFuv: '成功播放第一帧的独立用户数',
    playTime: '用户观看视频的总时长',
    useRate: '使用用户除以联网用户',
    playRate: 'FUV除以使用用户'
}

jQuery.download = function (url, data, method) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            var value = pair[1];
            if (pair[0] != 'columns') {
                value = LittleUrl.decode(pair[1])
            }
            inputs += '<input type="hidden" name="' + pair[0] + '" value="'
                + value + '" />';
        });
        jQuery(
            '<form action="' + url + '" method="' + (method || 'post')
                + '">' + inputs + '</form>').appendTo('body').submit()
            .remove();
    }
    ;
};

var LittleUrl = {
    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12)
                    | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
